//
//  dict.c
//  xxxxxx
//
//  Created by vence on 14-5-30.
//  Copyright (c) 2014年 vence. All rights reserved.
//

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "dict.h"
#include "defs.h"
int trie_count = 0;
static TrieNode root_node;
static TrieNode all_nodes[DICT_SIZE + 1000];
// global node count here; DO NOT build 2 tries at a time

TrieNode * trie_init()
{
    trie_count = 2;
    // printf("trie_count %d\n", trie_count);
    TrieNode *root = &root_node;
    memset(root,0,sizeof(TrieNode));
    memset(all_nodes, 0, sizeof(all_nodes));
    return root;
}

void trie_destroy( TrieNode *root)
{
    int i;
    memset(&root_node,0, sizeof(TrieNode));
    memset(all_nodes, 0, sizeof(all_nodes));
    trie_count=0;
}

TrieNode * trie_insert( TrieNode *node, char *word, int len)
{
    int i;
    int idx;
    TrieNode *cur=node;
    int current_count= trie_count;

    for(i=0;i<len;i++)
    {
        if(cur->next[word[i]&0xff]==NULL)
        {
            TrieNode *newNode = (TrieNode *)malloc(sizeof(TrieNode));
            memset(newNode,0,sizeof(TrieNode));
            newNode->num= trie_count;
            // printf("%c %d\n", word[i], newNode->num);
            cur->next[word[i]&0xff]=(struct TrieNode *)newNode;
        }
        cur=(TrieNode *)cur->next[word[i] & 0xff];
    }
    trie_count++;
    return cur;
}

TrieNode * trie_lookup(TrieNode *node,char *word,int len)       //find if there is s in Trie
{                                                     //YES,return end Node;
    //NO, return NULL;
    int i;
    TrieNode *cur;
    cur=node;
    for(i=0;i<len;i++)
    {
        if(cur->next[word[i] & 0xff]==NULL)
        {
            return NULL;
        }
        cur=(TrieNode *)cur->next[word[i] & 0xff];
    }
    return cur;
}

TrieNode * trie_lookup_c( TrieNode *node, char ch)
{
    return (TrieNode *)node->next[ch&0xff];
}

TrieNode * trie_insert_c(TrieNode *node, char ch)
{   
    TrieNode *newNode = all_nodes + trie_count;
    newNode->num = trie_count;
    trie_count++;
    node->next[ch&0xff] = (struct TrieNode *)newNode;
    return newNode;
}

TrieNode * trie_insert_i(TrieNode *node, unsigned idx)
{   
    TrieNode *newNode = all_nodes + trie_count;
    newNode->num = trie_count;
    trie_count++;
    node->next[idx] = (struct TrieNode *)newNode;
    return newNode;
}
